#include "mySort.h"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
 
// 默认构造函数，初始化num为0，origin指针为nullptr
MySort::MySort() : num(0), origin(nullptr) {}

// 带参数的构造函数，接收元素个数和原始数组，初始化num和origin
MySort::MySort(int n, int* o) : num(n), origin(new int[n]) {
    for (int i = 0; i < n; ++i) {
        origin[i] = o[i]; 
    }
}

// 析构函数，释放origin指向的动态内存
MySort::~MySort() {
    delete[] origin;
}

// 输出当前序列的辅助函数
void MySort::outputCurrentSequence(int* array) {
    ostringstream oss; 
    for (int j = 0; j < num; ++j) {
        oss << array[j]; 
        if (j < num - 1) {
            oss << " "; 
        }
    }
    oss << "\n"; 
    cout << oss.str(); 
}

// 奇偶交换排序
string MySort::paritySort() {
    int* temp = new int[num]; 
    for (int i = 0; i < num; ++i) {
        temp[i] = origin[i]; 
    }
    bool swapped; 
    do {
        swapped = false;
        // 奇数位置排序
        for (int i = 1; i < num - 1; i += 2) {
            if (temp[i] > temp[i + 1]) { 
                swap(temp[i], temp[i + 1]);
                swapped = true; 
                outputCurrentSequence(temp); 
            }
        }
        // 偶数位置排序
        for (int i = 0; i < num - 1; i += 2) {
            if (temp[i] > temp[i + 1]) { 
                swap(temp[i], temp[i + 1]);
                swapped = true; 
                outputCurrentSequence(temp); 
            }
        }
    } while (swapped); 

    // 将排序结果复制回 origin
    for (int i = 0; i < num; ++i) {
        origin[i] = temp[i];
    }

    delete[] temp; 

    // 最终结果输出部分已去掉
    return ""; 
}

// 双向冒泡排序
string MySort::bubbleSort() {
    int* temp = new int[num]; 
    for (int i = 0; i < num; ++i) {
        temp[i] = origin[i]; 
    }
    bool swapped; 
    do {
        swapped = false; 
        // 从左到右冒泡
        for (int i = 0; i < num - 1; ++i) {
            if (temp[i] > temp[i + 1]) { 
                swap(temp[i], temp[i + 1]);
                swapped = true; 
                outputCurrentSequence(temp); 
            }
        }
        // 从右到左冒泡
        for (int i = num - 1; i > 0; --i) {
            if (temp[i] < temp[i - 1]) { 
                swap(temp[i], temp[i - 1]);
                swapped = true; 
                outputCurrentSequence(temp); 
            }
        }
    } while (swapped); 

    // 将排序结果复制回 origin
    for (int i = 0; i < num; ++i) {
        origin[i] = temp[i];
    }
    
    delete[] temp; 

    // 最终结果输出部分已去掉
    return ""; 
}